/*
 * 文件名：ProSettleController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年2月22日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.bpa.web;


import com.github.pagehelper.Page;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.mgr.bpa.domain.ProSettleAssist;
import top.infopub.mgr.bpa.domain.ProSettleDomain;
import top.infopub.mgr.bpa.service.ContractExtInvestService;
import top.infopub.mgr.bpa.service.ContractExtService;
import top.infopub.mgr.bpa.service.ContractExtSubService;
import top.infopub.mgr.bpa.service.ProSettleService;
import top.infopub.mgr.bpa.vo.ProSettleVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.bpa.*;
import top.infopub.model.hr.OrgInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**结算管理
 * @author wuzhiyang
 * @version 2020年2月22日
 * @see ProSettleController
 * @since商务管理/结算管理/项目预(结)算
 */
@Controller
@RequestMapping("/proSettle")
public class ProSettleController extends GenericFlowController {

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private ProSettleService proSettleService;

    @Autowired
    private ContractExtService contractExtService;

    @Autowired
    private ContractExtInvestService contractExtInvestService;

    @Autowired
    private ContractExtSubService contractExtSubService;

    @Autowired
    private OrgInfoService orgInfoService;

    /**
     * 项目预(结)算列表
     * @return 
     * @see
     */
    @RequestMapping("/list")
    public String list() {
        return "bpa/lay-proSettle-list";
    }

    /**
     * 项目预(结)算列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ProSettleDomain> queryDataByCondition(ProSettleVo proSettleVo, ParamPage paramPage) {
        Page<ProSettleDomain> page = new Page<ProSettleDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (proSettleVo.getEndDate() != null) {
            proSettleVo.setEndDate(DateUtils.addDays(proSettleVo.getEndDate(), 1));
        }
        page = proSettleService.selectByDomainWhere(page, proSettleVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 项目预(结)算-我审批的列表数据
     *
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<ProSettleDomain> queryMyCheckDataByCondition(ProSettleVo proSettleVo,
                                                              ParamPage paramPage) {
        Page<ProSettleDomain> page = new Page<ProSettleDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (proSettleVo.getEndDate() != null) {
            proSettleVo.setEndDate(DateUtils.addDays(proSettleVo.getEndDate(), 1));
        }
        proSettleVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = proSettleService.selectMyCheckByDomainWhere(page, proSettleVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

//    /**
//     * 项目预(结)算-新增
//     * @return
//     */
//    @RequestMapping("/add")
//    public String toAdd(HttpServletRequest request) {
//        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
//        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
//        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
//        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
//        request.setAttribute("bindOrgId", bindOrgId);
//        request.setAttribute("bindOrgName", bindOrgName);
//        request.setAttribute("bindDeptId", bindDeptId);
//        request.setAttribute("bindDeptName", bindDeptName);
//        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
//        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
//        request.setAttribute("staffName", staffInfo.getStaffName());
//        //返回所有承继协议中的项目名称
//        List<ContractExt> contractExtList = contractExtService.queryAllExts();
//        request.setAttribute("contractExtList", contractExtList);
//        return "bpa/lay-proSettle-add";
//    }

//    /**
//     * 根据承继协议中项目编号查询相关带入信息
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/getProSettleByProCode")
//    @ResponseBody
//    public Map<String, Object> getProSettleByProCode(HttpServletRequest request) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        String proCodeAndCodes = request.getParameter("proCodeAndCodes");
//        String[] proCodes = proCodeAndCodes.split("\\_");
//        try {
//            //带出内部协议的信息
//            Map<String, Object> mapWhere = new HashMap<String, Object>();
//            ContractExtDomain contractExtDomain = new ContractExtDomain();
//            mapWhere.put("refId", proCodes[1]);
//            mapWhere.put("processStatus", "9");
//            mapWhere.put("orderCondition", "ADD_TIME desc");
//            List<ContractExt> contractExts = contractExtService.selectByMapWhere(mapWhere);
//            if (CollectionUtils.isNotEmpty(contractExts)) {
//                contractExtDomain = contractExtService.selectByIds(contractExts.get(0).getId());
//            }
//            else {
//                contractExtDomain = contractExtService.selectByIds(proCodes[1]);
//            }
//            if (contractExtDomain != null) {
//                map.put("contractExtDomain", contractExtDomain);
//                //带出子项名称
//                ContractExtSub contractExtSub = new ContractExtSub();
//                contractExtSub.setContractExtId(contractExtDomain.getId());
//                List<ContractExtSub> contractExtSubList = contractExtSubService.selectByEntityWhere(contractExtSub);
//                map.put("contractExtSubList", contractExtSubList);
//                //带出承继协议投资信息
//                ContractExtInvest contractExtInvest = contractExtInvestService.selectLatestContractExtInvestByExtId(contractExtDomain.getId());
//                map.put("contractExtInvest", contractExtInvest);
//            }
//            else {
//                flag = false;
//            }
//        }
//        catch (Exception e) {
//            log.error("查询承继协议记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

    /**
     * 项目预(结)算-新增
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(ProSettleAssist proSettleAssist) {

        //主表-项目预(结)算
        proSettleAssist.setHrDeptId(proSettleAssist.getHrDeptid());
        proSettleAssist.setHrOrgId(proSettleAssist.getHrOrgid());
        proSettleAssist.setStaffName(proSettleAssist.getStaffname());
        proSettleAssist.setHrStaffApplyId(proSettleAssist.getHrStaffApplyid());
        String proCode = "";
        String code = "";
        String[] strCodes = proSettleAssist.getProCodeAndCodes().split("\\_");
        proCode = strCodes[0];
        code = strCodes[1];
        proSettleAssist.setRefId(code);
        proSettleAssist.setProCode(proCode);
        proSettleAssist.setProName(strCodes[2]);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();

        proSettleAssist.setId(id);
        proSettleAssist.setAddBy(vo.getId());
        proSettleAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("bpa_pro_settle");
        proSettleAssist.setCodes(codes);
        // 处理processId
        proSettleAssist.setProcessId(IdFactory.getUUIDUpper());
        proSettleAssist.setProcessStatus("1");//审批中
        proSettleAssist.setTypes("1");//PPP项目
        proSettleAssist.setUptBy(vo.getId());
        proSettleAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //项目预（结）算明细 detail    
        List<ProSettleDetail> proSettleDetails = new ArrayList<ProSettleDetail>();
        if (!"1".equals(proSettleAssist.getBudgetType())) {
            //费用大类
            String[] showIdxs = proSettleAssist.getShowIdxs();
            for (int j = 0; j < showIdxs.length; j++ ) {
                String showIdx = showIdxs[j];
                String itemName = proSettleAssist.getItemNames()[j];
                String subName = proSettleAssist.getSubNames()[j];
                String feeType = proSettleAssist.getFeeTypes()[j];
                String cotAmountAfter = proSettleAssist.getCotAmountAfters()[j];
                String applyAmount = proSettleAssist.getApplyAmounts()[j];
                String checkAmount = proSettleAssist.getCheckAmounts()[j];
                String checkAmountRevise = proSettleAssist.getCheckAmountRevises()[j];
                String checkReviseRate = proSettleAssist.getCheckReviseRates()[j];
                if (StringUtils.isEmpty(showIdx) && StringUtils.isEmpty(showIdx)) {
                    continue;
                }
                ProSettleDetail proSettleDetail = new ProSettleDetail();
                String proSettleDetailId = IdFactory.getUUIDUpper();//自动生成主键
                proSettleDetail.setId(proSettleDetailId);
                proSettleDetail.setProSettleId(id);
                proSettleDetail.setShowIdx(Integer.parseInt(showIdx));
                proSettleDetail.setItemName(itemName);
                proSettleDetail.setSubName(subName);
                proSettleDetail.setFeeType(feeType);
                proSettleDetail.setCotAmountAfter(new BigDecimal(cotAmountAfter));
                proSettleDetail.setApplyAmount(new BigDecimal(applyAmount));
                proSettleDetail.setCheckAmount(new BigDecimal(checkAmount));
                proSettleDetail.setCheckAmountRevise(new BigDecimal(checkAmountRevise));
                proSettleDetail.setCheckReviseRate(new BigDecimal(checkReviseRate));
                proSettleDetail.setAddBy(vo.getId());
                proSettleDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                proSettleDetails.add(proSettleDetail);
            }

        }
        //项目预（结）算合同费用信息 fee
        ProSettleFee proSettleFee = new ProSettleFee();
        String proSettleFeeId = IdFactory.getUUIDUpper();//自动生成主键
        proSettleFee.setId(proSettleFeeId);
        proSettleFee.setProSettleId(id);
        proSettleFee.setAddBy(vo.getId());
        proSettleFee.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        //接收前端的值
        proSettleFee.setCaeFee(proSettleAssist.getCaeFee());
        proSettleFee.setCaeDownRate(proSettleAssist.getCaeDownRate());
        proSettleFee.setCaeRate(proSettleAssist.getCaeRate());
        proSettleFee.setPrepareFee(proSettleAssist.getPrepareFee());
        proSettleFee.setBuildOtherFee(proSettleAssist.getBuildOtherFee());
        proSettleFee.setBuildOrgFee(proSettleAssist.getBuildOrgFee());

        proSettleFee.setGdReplaceFee(proSettleAssist.getGdReplaceFee());
        proSettleFee.setPreFee(proSettleAssist.getPreFee());
        proSettleFee.setMoveFee(proSettleAssist.getMoveFee());
        proSettleFee.setBuildInterest(proSettleAssist.getBuildInterest());

        proSettleFee.setBuyFee(proSettleAssist.getBuyFee());
        proSettleFee.setFlowFee(proSettleAssist.getFlowFee());

        proSettleFee.setTotalSum(proSettleAssist.getTotalSumFee());

        //上传附件
        //1=计算稿
        List<ProSettleAtt> proSettleAtts = new ArrayList<ProSettleAtt>();
        String[] fileAtt1 = proSettleAssist.getFileAtts1();
        if (fileAtt1 != null) {
            for (String file : fileAtt1) {
                ProSettleAtt proSettleAtt = createFileAtt(vo, id, file);
                proSettleAtt.setTypes("1");
                proSettleAtts.add(proSettleAtt);
            }
        }
        //2=签字扫描件
        String[] fileAtt2 = proSettleAssist.getFileAtts2();
        if (fileAtt2 != null) {
            for (String file : fileAtt2) {
                ProSettleAtt proSettleAtt = createFileAtt(vo, id, file);
                proSettleAtt.setTypes("2");
                proSettleAtts.add(proSettleAtt);
            }
        }
        //3=其他附件
        String[] fileAtt3 = proSettleAssist.getFileAtts3();
        if (fileAtt3 != null) {
            for (String file : fileAtt3) {
                ProSettleAtt proSettleAtt = createFileAtt(vo, id, file);
                proSettleAtt.setTypes("3");
                proSettleAtts.add(proSettleAtt);
            }
        }

        proSettleService.saveProSettle(proSettleAssist, proSettleDetails, proSettleAtts,
            proSettleFee);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "商务管理 -结算管理-项目预(结)算：项目名="
                                                              + proSettleAssist.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    private ProSettleAtt createFileAtt(AuthorizationVO vo, String proSettleId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        ProSettleAtt fileAtt = new ProSettleAtt();
        if (StringUtils.isNotEmpty(fileAttStr[2])) {
            fileAtt.setId(fileAttStr[2]);
        }
        else {
            fileAtt.setId(IdFactory.getUUIDSerialNumber());
        }
        fileAtt.setProSettleId(proSettleId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "proSettle";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传结算管理-项目预(结)算附件-文件名:"
                                                                      + filePath + "，文件路径:"
                                                                      + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询设备合同详细  > 注意：方法命名必须为：toDealOrDetail
     *
     * @param id 项目预(结)算id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        ProSettleVo proSettleVo = proSettleService.queryById(id);
        OrgInfo orgInfo = new OrgInfo();
        orgInfo.setProjectCode(proSettleVo.getProCode());
        orgInfo.setState(1);
        List<OrgInfo> orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        if (orgInfos.size() > 0) {
            proSettleVo.setOrgProName(orgInfos.get(0).getCompName());
            proSettleVo.setHrOrgProId(orgInfos.get(0).getId());
            OrgInfo parentOrgInfo = new OrgInfo();
            parentOrgInfo.setId(orgInfos.get(0).getParentId());
            parentOrgInfo.setState(1);
            List<OrgInfo> parentOInfos = orgInfoService.selectByEntityWhere(parentOrgInfo);
            if (parentOInfos.size() > 0) {
                proSettleVo.setOrgAreName(parentOInfos.get(0).getCompName());
                proSettleVo.setHrOrgAreaId(parentOInfos.get(0).getId());
            }
        }
        request.setAttribute("modelDetail", proSettleVo);
        map.put("proSettleVo", proSettleVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, proSettleVo.getProcessId());
        return new ModelAndView("bpa/lay-proSettle-detail", map);
    }

    /**
     * 项目预(结)算-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request) {
        String id = request.getParameter("id");
        String refId = request.getParameter("refId");
        ProSettleVo proSettleVo = proSettleService.queryById(id);
        request.setAttribute("proSettleVo", proSettleVo);
        //带出子项名称
        Map<String, Object> mapWhere = new HashMap<String, Object>();
        mapWhere.put("refId", refId);
        mapWhere.put("processStatus", "9");
        mapWhere.put("orderCondition", "ADD_TIME desc");
        List<ContractExt> contractExts = contractExtService.selectByMapWhere(mapWhere);
        if(CollectionUtils.isNotEmpty(contractExts)){
            ContractExt contractExt = contractExts.get(0);
            ContractExtSub contractExtSub = new ContractExtSub();
            contractExtSub.setContractExtId(contractExt.getId());
            List<ContractExtSub> contractExtSubList = contractExtSubService.selectByEntityWhere(contractExtSub);
            request.setAttribute("contractExtSubList", contractExtSubList);
        }
        return "bpa/lay-proSettle-copy";
    }

}
